import { departmentApi, iuserById, roleApi } from '@T2/service/api.ts';
import { buildTree, findNodeByProperty } from '@T2/utils/utils.ts';
import { useCurrentWatchStore, useIuserInfoStore, useLocalMenusStore } from '@T2/store/users.ts';
import type { ProjectDetailType, CurrentMenuType } from '@T2/store/users.ts';

interface DepartmentType {
  company: number;
  id: number;
  name: string;
  parent: null | number;
  projects: number[];
  units: number[];
  units_flag: string;
  children?: DepartmentType[];
  [key: string]: any;
}
export const getDepartmentList = async (filterProject: boolean = true, filterDepartment: boolean = true) => {
  const iuserInfoStore = useIuserInfoStore();
  const { created_company, info } = iuserInfoStore;
  const isCoSuper = created_company === info.company;
  const currentWatchStore = useCurrentWatchStore();
  const { curProject } = currentWatchStore;
  
  const filterTree = (tree: DepartmentType[]) => {
    /* 筛选出包含当前项目的组织 */
    function filterNode(node: DepartmentType) {
      if (!curProject.id || !node.projects.includes(curProject.id)) {
        return null;
      }
      const filteredChildren = node.children?.map(node => filterNode(node)).filter(Boolean) || [];
      return { ...node, children: filteredChildren };
    }
    return tree.map(node => filterNode(node)).filter(Boolean);
  }
  
  const { results } = await departmentApi({
    method: 'get',
    params: {
      ordering: 'id',
    }
  }) as unknown as {results: DepartmentType[]};
  if (!results) {
    return [];
  }
  const treeBasic = buildTree(results || [], 'parent') as DepartmentType[];
  if (!filterProject && !filterDepartment) {
    return treeBasic;
  }
  let tree = filterProject ? filterTree(treeBasic) : treeBasic;
  if (!filterDepartment) {
    return tree;
  }
  const departmentID = info.department?.department;
  if (isCoSuper) {
    return tree;
  } else if (departmentID) {
    const department = findNodeByProperty(tree, 'id', departmentID);
    if (department) {
      return [department];
    } else {
      return [];
    }
  }
}

interface IuserType {
  id: number;
  truename: string;
  department: number | null;
  department_name: string | null;
  projects: number[];
  project_roles: number[];
  [key: string]: any;
}
interface RoleType {
  id: number;
  name: string;
  projects: number[];
}
export const getIuserProjectRoleStr = async (iuserID: number) => {
  let iuser: IuserType | null = null;
  const getRoleStr = async () => {
    let roles: RoleType[] = [];
    
    const getIuser = (id: number) => {
      return new Promise((resolve, reject) => {
        iuserById({
          method: 'get',
          id,
        }).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        })
      })
    };
    const getRoles = () => {
      return new Promise((resolve, reject) => {
        roleApi({
          method: 'get',
          params: {}
        }).then((res: any) => {
          resolve(res?.results || []);
        }).catch(err => {
          reject(err);
        })
      })
    };
    const [iuserResult, rolesResult] = await Promise.all([getIuser(iuserID), getRoles()]);
    iuser = iuserResult as IuserType;
    roles = rolesResult as RoleType[];
    
    const rolesValids = roles.filter(role => iuser?.project_roles?.includes(role.id));
    if (rolesValids.length) {
      return rolesValids.map(i => i.name).join(',');
    }
    
    const iuserInfoStore = useIuserInfoStore();
    const { admin_projects2, created_company, info } = iuserInfoStore;
    if (created_company === info.company) {
      return '超级管理员';
    }
    
    const currentWatchStore = useCurrentWatchStore();
    const { curProject } = currentWatchStore;
    if (curProject?.id && admin_projects2.includes(curProject.id)) {
      return '项目管理员';
    }
    
    return '';
  }
  
  return { roleStr: await getRoleStr(), iuserInfo: iuser };
}

export const getToSomeProjectPath = (projectID?: number): string => {
  const localMenusStore = useLocalMenusStore();
  const proListsMenu = localMenusStore.getProListsMenuOfPC;
  const currentWatchStore = useCurrentWatchStore();
  const projectList = currentWatchStore.getProjectsOfValidMenus;
  
  if (!proListsMenu.length) {
    return '';
  }
  
  let curProject: ProjectDetailType, curMenus: { children: CurrentMenuType[]; project: number; };
  if (projectID === undefined) {
    const [ pArray0 ] = proListsMenu;
    curProject = projectList.find(item => item.id === pArray0?.project) as ProjectDetailType;
    curMenus = pArray0;
  } else {
    curProject = projectList.find(item => item.id === projectID) as ProjectDetailType;
    curMenus = proListsMenu.find(i => i.project === projectID) as { children: CurrentMenuType[]; project: number; };
  }
  currentWatchStore.setLevel('project');
  currentWatchStore.setCurMenus(curMenus?.children || []);
  currentWatchStore.setCurProject(curProject);
  
  let path = '/P/Manage';
  if (curProject.css === '2-2' || !curMenus?.children.find(item => item.type === 'PC-aside')) {
    path = '/P/Display';
  }
  return path;
}

export const getToCompanyPath = () : string => {
  const localMenusStore = useLocalMenusStore();
  const companyMenu = localMenusStore.getCoMenusOfPC;
  
  if (!companyMenu.length) {
    return '';
  }
  
  const currentWatchStore = useCurrentWatchStore();
  currentWatchStore.setLevel('company');
  currentWatchStore.setCurMenus(companyMenu);
  currentWatchStore.setCurProject({});
  
  return companyMenu.find(item => item.type === 'PC-aside') ? '/C/Manage' : '/C/Display';
}